package com.delicious.core.dict.service;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.delicious.core.base.BaseResponse;
import com.delicious.core.dict.vo.DictTypePageRequest;
import com.delicious.core.dict.vo.DictTypePageResponse;
import com.delicious.core.dict.vo.DictTypeRequest;
import com.delicious.core.dict.vo.DictTypeResponse;
import com.delicious.core.dict.convert.DictTypeConverter;
import com.delicious.core.dict.entity.SysDictType;
import com.delicious.core.dict.mapper.SysDictTypeMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
public class SysDictTypeService {

    @Resource
    private SysDictTypeMapper sysDictTypeMapper;
    @Resource
    private DictTypeConverter dictTypeConverter;

    public Page<DictTypePageResponse> listDictTypePages(DictTypePageRequest queryParams) {
        // 查询参数
        int pageNum = queryParams.getPageNum(); // 1
        int pageSize = queryParams.getPageSize(); // 10
        String keywords = queryParams.getKeywords();

        // 查询数据
        Page<SysDictType> dictTypePage = sysDictTypeMapper.selectPage(
                new Page<>(pageNum, pageSize),
                new LambdaQueryWrapper<SysDictType>()
                        .like(StrUtil.isNotBlank(keywords), SysDictType::getName, keywords)
                        .or()
                        .like(StrUtil.isNotBlank(keywords), SysDictType::getCode, keywords)
                        .select(SysDictType::getId, SysDictType::getName, SysDictType::getCode, SysDictType::getStatus)
        );

        // 实体转换
        Page<DictTypePageResponse> pageResult = dictTypeConverter.entity2Page(dictTypePage);
        return pageResult;
    }

    public DictTypeResponse getDictTypeFormData(Long id) {
        // 获取entity
        SysDictType entity = sysDictTypeMapper.selectOne(new LambdaQueryWrapper<SysDictType>()
                .eq(SysDictType::getId, id)
                .select(
                        SysDictType::getId,
                        SysDictType::getName,
                        SysDictType::getCode,
                        SysDictType::getStatus,
                        SysDictType::getRemark
                ));
        Assert.isTrue(entity != null, "字典类型不存在");

        return dictTypeConverter.entity2Form(entity);
    }

    public BaseResponse saveDictType(DictTypeRequest request) {
        // 实体对象转换 form->entity
        SysDictType entity = dictTypeConverter.form2Entity(request);
        if (request.getId() != null) {
            sysDictTypeMapper.updateById(entity);
        } else {
            sysDictTypeMapper.insert(entity);
        }
        return BaseResponse.success();
    }
}
